<template>
	<view class="container">
		<!-- 顶部标题栏 -->
		<view class="header">
			<text class="header-title">设置</text>
		</view>
		<!-- 头像和昵称 -->
		<view class="section">
			<view class="item" @tap="toggleAvatarModal">
				<text class="label">头像</text>
				<view class="content">
					<image :src=image class="avatar"></image>
				</view>
			</view>
			<view class="item">
				<text class="label">昵称</text>
				<view class="content" @click="toggleNicknameModal">
					<text>{{username}}</text>
					<image src="/static/motif/xiayibu1.png" class="arrow"></image>
				</view>
			</view>

			<u-modal :show="showNicknameModal" title="修改昵称" @close="toggleNicknameModal" :show-footer="false"
				@confirm="updateNickname">
				<view class="modal-body">
					<u-input v-model="newNickname" placeholder="请输入新的昵称" clearable />
				</view>
				<view class="modal-footer">
					<u-button type="default" @click="toggleNicknameModal">取消</u-button>
				</view>
			</u-modal>

			<view class="item">
				<text class="label">手机号</text>
				<view class="content" @click="toggleNickPhone">
					<text>{{maskedPhone}}</text>
					<image src="/static/motif/xiayibu1.png" class="arrow"></image>
				</view>
			</view>

			<u-modal :show="showPhoneModal" title="修改手机号" @close="toggleNickPhoneModal" :show-footer="false"
				@confirm="updatePhonename">
				<view class="modal-body">
					<u-input v-model="newPhoneModal" placeholder="请输入新的手机号" clearable />
				</view>
				<view class="modal-footer">
					<u-button type="default" @click="toggleNickPhoneModal">取消</u-button>
				</view>
			</u-modal>


		</view>

		<!-- 其他设置选项 -->
		<view class="section">
			<view class="item" @click="showAboutPopup">
				<text class="label">关于</text>
				<view class="arrow1">></view>
			</view>
			<view class="item" @click="showFeedbackPopup">
				<text class="label">意见反馈</text>
				<view class="arrow1">></view>
			</view>
		</view>

		<!-- 关于弹窗 -->
		<view v-if="showAbout" class="popup">
			<view class="popup-content">
				<text class="popup-title">关于</text>
				<text class="popup-text">V我50</text>
				<view class="popup-close" @click="closePopup('about')">关闭</view>
			</view>
		</view>

		<!-- 意见反馈弹窗 -->
		<view v-if="showFeedback" class="popup">
			<view class="popup-content">
				<text class="popup-title">意见反馈</text>
				<text class="popup-text">请留下您的宝贵意见。</text>
				<view class="popup-close" @click="closePopup('feedback')">关闭</view>
			</view>
		</view>

		<!-- 修改密码、退出登录按钮 -->
		<view class="logout-section">
			<text class="button" @click="EditInfo">修改密码</text>
		</view>
		<view class="logout-section">
			<text class="logout-button" @click="out">退出登录</text>
		</view>


		<u-action-sheet :actions="lists" :show="showAvatarModal" @select="editAvater" closeOnClickOverlay
			@close="showAvatarModal=false"></u-action-sheet>
	</view>

</template>

<script>
	import {
		getuser,
		setUser,
		setPassword
	} from '@/api/user.js';
	export default {
		data() {
			return {
				showAbout: false, // 控制关于弹窗显示
				showFeedback: false, // 控制意见反馈弹窗显示
				fileList1: [],
				image: '', //头像
				username: '66666', //昵称
				newNickname: '', // 用于绑定新昵称输入框的值
				showNicknameModal: false, // 控制昵称弹窗的显示
				newNickname: '', // 用于绑定新昵称输入框的值
				phoneNumber: "17683198745", //手机号
				newPhoneModal: '', //新手机号
				showPhoneModal: false,
				showNicknameModal: false, // 控制昵称弹窗的显示
				showAvatarModal: false, // 控制头像弹窗的显示
				lists: [{
						name: '更换头像',
						color: '',
						fontSize: 28,
					},
					{
						name: '查看大图',
						color: '',
						fontSize: 28,
					}
				]
			};
		},
		computed: {
			maskedPhone() {
				return this.phoneNumber ? this.phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2") : "";
			}
		},

		methods: {
			// 显示关于弹窗
			showAboutPopup() {
				this.showAbout = true;
			},
			// 显示意见反馈弹窗
			showFeedbackPopup() {
				this.showFeedback = true;
			},
			// 关闭弹窗
			closePopup(popupType) {
				if (popupType === 'about') {
					this.showAbout = false;
				} else if (popupType === 'feedback') {
					this.showFeedback = false;
				}
			},
			//手机号的弹窗
			toggleNickPhone() {
				this.showPhoneModal = !this.showPhoneModal;
				if (this.showPhoneModal) {
					this.newPhoneModal = this.phoneNumber;
				}
			},
			toggleNickPhoneModal() {
				this.showPhoneModal = false
				this.newNickname = ''
			},
			updatePhonename() {
				// 去除前后空格后判断手机号是否为空
				if (!this.newPhoneModal.trim()) {
					uni.showToast({
						title: '手机号不能为空',
						icon: 'none',
					});
					return;
				}
				// 手机号格式校验（中国大陆手机号）
				const phoneRegEx = /^1[3-9]\d{9}$/; // 以1开头，第二位为3-9之间的数字，后面跟随9个数字
				if (!phoneRegEx.test(this.newPhoneModal.trim())) {
					uni.showToast({
						title: '请输入有效的手机号',
						icon: 'none',
					});
					return;
				}
				setUser({
					userId: this.$cookies.get("id"),
					userPhone: this.newPhoneModal.trim(),
				}).then((res) => {
					this.phoneNumber = this.newPhoneModal.trim();
					uni.showToast({
						title: '手机号更新成功',
						icon: 'success',
					});

					this.toggleNickPhoneModal(); // 关闭弹窗
				}).catch((error) => {
					// 错误处理
					uni.showToast({
						title: '更新失败，请稍后重试',
						icon: 'none',
					});
					console.error(error);
				});
			},
			// 切换昵称弹窗显示状态
			toggleNicknameModal() {
				this.showNicknameModal = !this.showNicknameModal;
				if (this.showNicknameModal) {
					this.newNickname = this.username; // 打开弹窗时填充当前昵称
				}
			},
			// 更新昵称的方法
			updateNickname() {
				// 去除前后空格后判断昵称是否为空
				const trimmedNickname = this.newNickname.trim();
				if (!trimmedNickname) {
					uni.showToast({
						title: '昵称不能为空',
						icon: 'none',
					});
					return;
				}

				// 校验昵称长度（可以自定义长度范围）
				if (trimmedNickname.length < 2 || trimmedNickname.length > 20) {
					uni.showToast({
						title: '昵称长度应在2到20个字符之间',
						icon: 'none',
					});
					return;
				}
				// 校验昵称是否包含非法字符（只允许字母、数字、汉字和常见符号）
				const nicknameRegEx = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/; // 只允许字母、数字和汉字
				if (!nicknameRegEx.test(trimmedNickname)) {
					uni.showToast({
						title: '昵称包含非法字符',
						icon: 'none',
					});
					return;
				}

				// 调用API更新昵称
				setUser({
					userId: this.$cookies.get("id"),
					userName: trimmedNickname, // 去掉空格后的昵称
				}).then((res) => {
					this.username = trimmedNickname; // 更新本地显示的昵称
					uni.showToast({
						title: '昵称更新成功',
						icon: 'success',
					});
					this.toggleNicknameModal(); // 关闭弹窗
				}).catch((error) => {
					// 错误处理
					uni.showToast({
						title: '更新失败，请稍后重试',
						icon: 'none',
					});
					console.error(error);
				});
			},

			editAvater(item) {
				if (item.name == "更换头像") {
					uni.chooseImage({
						count: 1, // 限制选择一张图片
						sizeType: ['original', 'compressed'], // 原图或压缩图
						sourceType: ['album', 'camera'], // 选择来源：相册或拍照
						success: (res) => {
							const tempFilePath = res.tempFilePaths[0];
							this.uploadImage(tempFilePath);
						},
						fail: (err) => {
							console.error('图片选择失败', err);
						}
					})
				}
			},
			// 上传图片到服务器
			uploadImage(filePath) {
				uni.showLoading({
					title: '正在上传图片...',
					mask: true
				});
				uni.uploadFile({
					url: this.uploadBaseUrl + "shopping-upload/upload/image",
					filePath: filePath,
					name: 'file',
					success: (uploadRes) => {
						uni.hideLoading();
						if (uploadRes.data.startsWith("/upload/image/")) {
							this.image = uploadRes.data;
							console.log('上传返回数据：', this.image);
							uni.showToast({
								title: '上传成功',
								icon: 'success'
							});
							setUser({
								userId: this.$cookies.get("id"),
								userImage: this.image
							}).then(res => {
								this.getlistuser();
							})
						} else {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('图片上传失败', err);
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						});
					}
				});
			},
			getlistuser() {
				getuser({
					userId: this.$cookies.get("id")
				}).then(res => {
					if (res.message == "success") {
						this.username = res.data.userName || "未设置昵称";
						this.phoneNumber = res.data.userPhone || "未绑定手机号";
						this.image = this.imgBaseUrl + res.data.userImage;
					} else {
						uni.showToast({
							type: 'error',
							icon: 'none',
							title: '获取失败'
						});
					}
				})
			},
			// 跳转到编辑信息页面
			EditInfo() {
				uni.navigateTo({
					url: '/pages/profile/editInfo'
				});
			},
			// 切换头像弹窗的显示状态
			toggleAvatarModal() {
				this.showAvatarModal = true
			},
			out() {
				// 弹出确认退出的对话框
				uni.showModal({
					title: '退出登录',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							this.$cookies.remove("id");
							this.$cookies.remove("token");
							uni.navigateTo({
								url: '/pages/login/login'
							});
						} else if (res.cancel) {
							console.log('用户取消退出');
						}
					}
				});
			}
		},
		onLoad() {
			this.getlistuser();

		}

	}
</script>


<style scoped>
	/* 弹窗遮罩 */
	.popup {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.6);
		/* 增加透明度，更加突出弹窗 */
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	/* 弹窗内容 */
	.popup-content {
		background-color: #fff;
		padding: 20px;
		border-radius: 10px;
		width: 80%;
		/* 宽度根据需要调整 */
		max-width: 400px;
		/* 最大宽度 */
		text-align: center;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
		/* 添加阴影使弹窗更加立体 */
	}

	/* 弹窗标题 */
	.popup-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 10px;
		display: block;
		/* 确保每个元素占据一行 */
		color: #333;
	}

	/* 弹窗文本内容 */
	.popup-text {
		font-size: 16px;
		color: #555;
		margin-bottom: 20px;
		display: block;
		/* 确保每个元素占据一行 */
	}

	/* 关闭按钮 */
	.popup-close {
		font-size: 16px;
		color: #007AFF;
		/* 关闭按钮颜色 */
		cursor: pointer;
		font-weight: bold;
	}

	.popup-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 15px;
	}

	.popup-text {
		font-size: 14px;
		color: #666;
		margin-bottom: 20px;
	}

	.popup-close {
		font-size: 16px;
		color: #007AFF;
		cursor: pointer;
	}

	.modal-body {
		padding: 20px 0;
	}

	.modal-footer {
		display: flex;
		justify-content: space-between;
		padding-top: 10px;
	}

	.modal-footer .u-button {
		flex: 1;
		margin: 0 5px;
	}

	/* 页面容器 */
	.container {
		background-color: #f5f6fa;
		height: 100vh;
		padding: 15px;
		display: flex;
		flex-direction: column;
		align-items: center;
		font-family: Arial, sans-serif;
	}

	/* 顶部标题栏 */
	.header {
		background-color: #2ac2d2;
		display: flex;
		align-items: center;
		padding: 15px 20px;
		color: #fff;
		width: 100%;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		border-radius: 10px;
		margin-bottom: 20px;
	}

	.back-arrow {
		width: 24px;
		height: 24px;
		margin-right: 10px;
		cursor: pointer;
	}

	.header-title {
		font-size: 20px;
		font-weight: bold;
	}

	/* 设置项的容器 */
	.section {
		width: 100%;
		background-color: #ffffff;
		border-radius: 10px;
		padding: 10px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
		margin-bottom: 15px;
	}

	/* 设置项 */
	.item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px 20px;
		border-bottom: 1px solid #f0f0f0;
	}

	.item:last-child {
		border-bottom: none;
	}

	.label {
		font-size: 16px;
		color: #333;
	}

	.content {
		display: flex;
		align-items: center;
	}

	.avatar {
		width: 60px;
		height: 60px;
		border-radius: 50%;
		object-fit: cover;
		border: 1px solid #ddd;
		margin-right: 10px;
	}

	.arrow {
		width: 16px;
		height: 16px;
		margin-left: 5px;
		cursor: pointer;
	}

	.arrow1 {
		color: #999;
		font-size: 18px;
		margin-left: 5px;
		cursor: pointer;
	}

	/* 退出登录和编辑信息按钮 */
	.logout-section {
		width: 90%;
		margin-top: 20px;
		text-align: center;
	}

	.button,
	.logout-button {
		display: block;
		width: 100%;
		padding: 12px;
		font-size: 16px;
		font-weight: bold;
		border-radius: 10px;
		cursor: pointer;
		margin-top: 10px;
		transition: all 0.3s;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	}

	.button {
		background-color: #2ac2d2;
		color: #fff;
	}

	.button:hover {
		background-color: #1da1b6;
		box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
	}

	.logout-button {
		background-color: #fff;
		color: #f44336;
		border: 1px solid #f44336;
	}

	.logout-button:hover {
		background-color: #f44336;
		color: #fff;
		box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
	}

	/* 头像弹窗样式 */
	.avatar-modal {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.modal-content {
		background-color: #fff;
		padding: 20px;
		border-radius: 10px;
		width: 200px;
		text-align: center;
	}

	.modal-title {
		margin-bottom: 20px;
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 20px;
	}

	.modal-options button {
		display: block;
		width: 100%;
		padding: 10px;
		margin: 10px 0;
		background-color: #2ac2d2;
		color: #fff;
		border: none;
		border-radius: 5px;
		font-size: 16px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.modal-options button:hover {
		background-color: #1da1b6;
	}

	.modal-close {
		margin-top: 10px;
		padding: 10px;
		font-size: 16px;
		color: black;
		cursor: pointer;
		background-color: skyblue;
		border: none;
	}
</style>